package vip.george.p0067;



public class P67 {

    public String addBinary(String a, String b) {
        StringBuilder sb = new StringBuilder();
        int al = a.length();
        int bl = b.length();
        int carry = 0;
        for (int i = al - 1, j = bl - 1; i >= 0 || j >= 0; i--, j--) {
            char aChar = i >= 0 ? a.charAt(i) : '0';
            char bChar = j >= 0 ? b.charAt(j) : '0';
            if (aChar == '1' && bChar == '1') {
                if (carry == 1) {
                    sb.append(1);
                } else {
                    sb.append(0);
                }
                carry = 1;
            } else if (aChar == '0' && bChar == '0') {
                if (carry == 1) {
                    sb.append(1);
                } else {
                    sb.append(0);
                }
                carry = 0;
            } else {
                if (carry == 1) {
                    sb.append(0);
                    // carry = 1; // 是否标识保持不变
                } else {
                    sb.append(1);
                    // carry = 0;
                }
            }
        }
        if (carry == 1) {
            sb.append(1);
        }
        return sb.reverse().toString();
    }

    public static void main(String[] args) {
        P67 p67 = new P67();
        System.out.println(p67.addBinary("11", "1"));
        System.out.println(p67.addBinary("1010", "1011"));
        System.out.println(p67.addBinary("1010111111", "1011"));
    }
}
